// stack_demo.c
// 栈的基本操作演示
#include <stdio.h>
#include <stdlib.h>

#define ElemType int
#define DEFAULT_SIZE 10

typedef struct stack {
    int top;
    int maxSize;
    ElemType *element;
} Stack;

// 函数声明
void InitStack(Stack *S, int size);
void Push(Stack *S, ElemType x);
ElemType Pop(Stack *S);
ElemType GetTop(Stack *S);
int IsEmpty(Stack *S);
int IsFull(Stack *S);
void DestroyStack(Stack *S);

int main() {
    Stack S;
    InitStack(&S, DEFAULT_SIZE);

    printf("初始化栈完成。\n");
    printf("开始入栈：10, 20, 30\n");
    Push(&S, 10);
    Push(&S, 20);
    Push(&S, 30);

    printf("当前栈顶元素：%d\n", GetTop(&S));

    printf("执行出栈操作...\n");
    printf("出栈元素：%d\n", Pop(&S));
    printf("出栈元素：%d\n", Pop(&S));

    printf("当前栈顶元素：%d\n", GetTop(&S));

    DestroyStack(&S);
    printf("栈已销毁。\n");

    return 0;
}

// 函数实现
void InitStack(Stack *S, int size) {
    S->element = (ElemType *)malloc(sizeof(ElemType) * size);
    if (!S->element) {
        printf("内存分配失败！\n");
        exit(1);
    }
    S->maxSize = size;
    S->top = -1;
}

int IsEmpty(Stack *S) {
    return S->top == -1;
}

int IsFull(Stack *S) {
    return S->top == S->maxSize - 1;
}

void Push(Stack *S, ElemType x) {
    if (IsFull(S)) {
        printf("栈满，无法入栈！\n");
        return;
    }
    S->element[++S->top] = x;
}

ElemType Pop(Stack *S) {
    if (IsEmpty(S)) {
        printf("栈空，无法出栈！\n");
        exit(1);
    }
    return S->element[S->top--];
}

ElemType GetTop(Stack *S) {
    if (IsEmpty(S)) {
        printf("栈空，无栈顶元素！\n");
        exit(1);
    }
    return S->element[S->top];
}

void DestroyStack(Stack *S) {
    free(S->element);
    S->element = NULL;
    S->top = -1;
    S->maxSize = 0;
}
